package com.android.readcard.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.android.readcard.R;
import com.android.readcard.adapter.BleAdapter;
import com.android.readcard.bean.ReadIccidAndWriteCardInfo;
import com.android.readcard.bean.WritePhoneNumInfo;
import com.android.readcard.dialog.MyUsualyDialog;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.android.readcard.eventbus.EventCodes;
import com.android.readcard.global.ConstantsValue;
import com.android.readcard.global.PrefReadCardTools;
import com.android.readcard.inter.ReadIccidListener;
import com.android.readcard.inter.WriteCardListener;
import com.android.readcard.utils.BleGlobUtils;
import com.android.readcard.utils.Busi_Idcard_device;
import com.android.readcard.utils.ToastUtils;
import com.android.readcard.utils.blluetooth.BluetoothManager;
import com.android.readcard.write.DjlmWrite;
import com.android.readcard.write.HHDWrite;
import com.android.readcard.write.Kt8000Write;
import com.android.readcard.write.Kt8003Write;
import com.android.readcard.write.SenRuiWrite;
import com.kaer.sdk.bt.BtReadClient;
import com.kaeridcard.client.BtReaderClient;
import com.sunnada.bluetooth.SYDBlueReaderHelper;

import java.util.ArrayList;
import java.util.Set;

import sunrise.bluetooth.SRBluetoothCardReader;


public class WriteCardActivity extends CardBaseActivity implements ReadIccidListener, WriteCardListener {

    // 卡尔参数
    private String krServerIp = "115.28.2.173";
    private String krAccount = "admin";
    private String krPassword = "www.kaer.cn";
    private String krftPort = "7443";

    // 森锐参数
    private String srSeverIp = "id.esaleb.com";
    private String srAccount = "test01";
    private String srPwd = "12315aA..1";
    private String srPort = "6100";
    private String srKey = "FE870B0163113409C134283661490AEF";

    private String strNam = ""; // 判断是否已添加
    private String strPeiDuiNam = "";  // 判断配对列表

    private int mType = 0; // 每次跳转的时候传递类型, // 0代表废卡重置,1代表写卡,2代表补卡

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_card);
        initView();
        initData(); // 初始化数据,获取读卡参数
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        // 接受到Event后的相关逻辑
        switch (event.getCode()) {
            case EventCodes.EventReadCardCode.C: // 带回短信中心号和imsi
                // 如果传回的值err是空的,就说明获取短信中心号成功了
                WritePhoneNumInfo mWritePhoneNumInfo = (WritePhoneNumInfo) event.getData();
                Log.e("项目异常写卡", event.getCode() + "------带回短信中心号和imsi------" + mWritePhoneNumInfo.toString());
                String phoneNum = mWritePhoneNumInfo.getPhoneNum();
                String imsi = mWritePhoneNumInfo.getImsi();
                String err = mWritePhoneNumInfo.getErr();

                if (TextUtils.isEmpty(err)) {
                    Log.e("项目异常写卡", "------TextUtils.isEmpty(err)------");
                    // 成功
                    switch (selectIndex) {
                        case 1:
                            byte[] szImsi = imsi.getBytes();
                            kt8000Write.writeKEardTask(szImsi, phoneNum);
                            break;
                        case 2:
                            byte[] szImsi1 = imsi.getBytes();
                            kt8003Write.writeIMSICardTask(szImsi1, phoneNum);
                            break;
                        case 3:
                            senRuiWrite.writeICCIDTask(imsi, phoneNum);
                            break;
                        case 4:
                            mHHDWrite.writeIccidData(imsi, "+86" + phoneNum);
                            break;
                        case 5:
                            mDjlmWrite.writeCard(imsi, phoneNum);
                            break;
                    }

                } else {
                    Log.e("项目异常写卡", "------TextUtils.isEmpty(err)2222------");
                    // 失败
                    dismissDialog();
                    closeReadCard(selectIndex);
                    finish();
                }
                break;
            case EventCodes.EventReadCardCode.E: // 废卡重置或者补卡写卡完成,关闭界面
                Log.e("项目异常写卡", event.getCode() + "------废卡重置或者补卡写卡完成,关闭界面------");
                closeReadCard(selectIndex);
                dismissDialog();
                finish();
                break;
        }
    }

    private static final int REQUEST_CODE_BLUETOOTH_ON = 1313;
    /**
     * Bluetooth 设备可见时间，单位：秒。
     */
    private static final int BLUETOOTH_DISCOVERABLE_DURATION = 250;

    /**
     * 弹出系统弹框提示用户打开 Bluetooth
     */
    private void turnOnBluetooth() {
        // 请求打开 Bluetooth
        Intent requestBluetoothOn = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);

        // 设置 Bluetooth 设备可以被其它 Bluetooth 设备扫描到
        requestBluetoothOn
                .setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

        // 设置 Bluetooth 设备可见时间
        requestBluetoothOn.putExtra(
                BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                BLUETOOTH_DISCOVERABLE_DURATION);

        // 请求开启 Bluetooth
        this.startActivityForResult(requestBluetoothOn,
                REQUEST_CODE_BLUETOOTH_ON);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // requestCode 与请求开启 Bluetooth 传入的 requestCode 相对应
        Log.e("项目异常lanya", requestCode + "-----onActivityResult------" + resultCode);
        if (requestCode == REQUEST_CODE_BLUETOOTH_ON) {

            if (resultCode==Activity.RESULT_CANCELED){
                finish();
            }else{
                initData();
            }
        }
    }

    // 开始搜索
    private void startSeach() {
        bleNameList = new ArrayList<>();
        bleAddressList = new ArrayList<>();
        bleAdapter = new BleAdapter(WriteCardActivity.this, bleNameList);
        lv_ble.setAdapter(bleAdapter);

        // 配对搜索
        SearchBts();
    }

    private void initView() {
        lv_ble = findViewById(R.id.lv_ble);
        pb_ble = findViewById(R.id.pb_ble);
        ll_shebei = findViewById(R.id.ll_shebei);
        ll_shebei.setVisibility(View.VISIBLE);
        dialog = new MyUsualyDialog(WriteCardActivity.this, R.layout.wait_item);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(false);
        ba = BluetoothAdapter.getDefaultAdapter();

        mType = getIntent().getIntExtra("WriteType", 0); // 每次跳转的时候传递类型,补卡/写卡/废卡重置
        Log.e("项目异常写卡", "------ReadIccidAndWriteCardInfo------" + mType);
        itemClick();
        stopRead();
    }

    /**
     * 连接读卡器
     *
     * @param readType
     * @param address
     */
    private void searchSuc(int readType, String address) {
        switch (readType) {
            case 1:
                kt8000Write = new Kt8000Write(WriteCardActivity.this, address, mType, this, this);
                kt8000Write.connect();
                break;
            case 2:
                kt8003Write = new Kt8003Write(WriteCardActivity.this, address, mType, this, this);
                kt8003Write.connect();
                break;
            case 3:

                int srPor = Integer.parseInt(srPort);
                SRBluetoothCardReader senmBlueReaderHelper = new SRBluetoothCardReader(mHandler, WriteCardActivity.this, srSeverIp, srPor,
                        srAccount, srPwd, srKey);
                senRuiWrite = new SenRuiWrite(WriteCardActivity.this, senmBlueReaderHelper, mType, address, this, this);
                senRuiWrite.connect();
                break;
            case 4:
                midHandler = new Busi_Idcard_device(WriteCardActivity.this);
                mIdUtil = new SYDBlueReaderHelper(midHandler.BmHanddler, WriteCardActivity.this);
                mHHDWrite = new HHDWrite(WriteCardActivity.this, mType, midHandler, mIdUtil, address, this, this);
                mHHDWrite.connect();
                break;
            case 5:
                mDjlmWrite = new DjlmWrite(WriteCardActivity.this, address, mType, this, this);
                mDjlmWrite.connect();
                break;

        }
    }

    /**
     * 条目点击事件
     */
    private void itemClick() {
        lv_ble.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                ll_shebei.setVisibility(View.GONE);
                mHandler.sendEmptyMessage(0);

                bleName = bleNameList.get(position);
                bleAddress = bleAddressList.get(position);
                remoteDevice = ba.getRemoteDevice(bleAddress);

                final int readType = quFenReadSheBei(bleName);

                // 获取读卡参数
                getReadNum(readType);
                Log.e("蓝牙异常", bleName + "====获取读卡参数=====:" + bleAddress);
                if (readType == 5) {
                    dialog.show();
                    // 店家联盟
                    searchSuc(readType, bleAddress);
                } else {
                    Log.e("蓝牙异常", bleName + "====获取读卡参数=====:" + strPeiDuiNam);
                    if (!bleName.contains("HOD") && !bleName.contains("SR")
                            && !bleName.contains("KT800") && !bleName.contains("DJLM")) {
                        showMsg(111, "该设备不能写卡");
                        return;
                    }

                    // 如果不是店家联盟,就要判断是否已配对
                    if (strPeiDuiNam.contains(bleName)) {
                        dialog.show();
                        if (readType == 1 || readType == 2) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    searchSuc(readType, bleAddress);
                                }
                            }).start();
                        } else {
                            searchSuc(readType, bleAddress);
                        }
                    } else {
                        BleGlobUtils.setDialog(WriteCardActivity.this);
                    }
                }
            }
        });
    }

    private String mIccidNum;

    @Override
    public void readIccidSuc(int count, String iccid, String imsi) {
        Log.e("项目异常写卡", iccid + "------readIccidSuc------" + imsi);
        mIccidNum = iccid;
        if (mType == 0) { // 如果是废卡重置,在读取iccid成功以后就关闭连接
            closeReadCard(selectIndex);
        }
        sendEvent(mType, mIccidNum, imsi, "", EventCodes.EventReadCardCode.B); // 0代表废卡重置,1代表写卡,2代表补卡
    }

    @Override
    public void readIccidErr(String err) { // 补卡/写卡读取iccid失败
        Log.e("项目异常写卡", "------readIccidErr------");
        dismissDialog();
        showMsg(111, err); // 直接Toast提示结果就行了
    }

    @Override
    public void readIccidIsChengKa(int index, String iccid, String err) { // 废卡重置失败结果
        Log.e("项目异常写卡", "------readIccidIsChengKa------" + err);
        closeReadCard(selectIndex);
        dismissDialog();
        showMsg(111, err); // 直接Toast提示结果就行了
    }

    @Override
    public void writeSuc() {
        Log.e("项目异常写卡", "------writeSuc------");
        closeReadCard(selectIndex);
        // 写卡成功,将数据返回,在APP项目里面去做处理
        sendEvent(mType, mIccidNum, "", "", EventCodes.EventReadCardCode.D); // 写卡成功错误信息返回空值,提交数据到服务器
    }

    @Override
    public void writeErr() {
        Log.e("项目异常写卡", "------writeErr------");
        dismissDialog();
        closeReadCard(selectIndex);

        sendEvent(mType, mIccidNum, "", "写卡失败,请重试", EventCodes.EventReadCardCode.D); // 写卡失败错误信息返回"写卡失败,请重试"
    }


    /**
     * 传递数据
     *
     * @param wrieType 0代表废卡重置,1代表写卡,2代表补卡
     * @param iccidNum iccid
     * @param imsi     没有imsi就传空
     * @param errMsg   没有错误信息就传空
     */
    private void sendEvent(int wrieType, String iccidNum, String imsi, String errMsg, int eventCode) {
        Log.e("项目异常写卡", wrieType + "------sendEvent------" + iccidNum +
                "------sendEvent------" + errMsg + "------sendEvent------" + eventCode);
        ReadIccidAndWriteCardInfo readIccidAndWriteCardInfo = new ReadIccidAndWriteCardInfo();
        readIccidAndWriteCardInfo.setWriteType(wrieType);
        readIccidAndWriteCardInfo.setIccidNum(iccidNum);
        readIccidAndWriteCardInfo.setImsi(imsi);
        readIccidAndWriteCardInfo.setErrMsg(errMsg);

        Event<ReadIccidAndWriteCardInfo> readIccidAndWriteCardInfoEvent = new Event<>(eventCode, readIccidAndWriteCardInfo);
        EventBusUtil.sendEvent(readIccidAndWriteCardInfoEvent);
    }

    /**
     * 区分是那种读卡器
     *
     * @param bleStrName 返回读卡器类型
     * @return
     */
    private int quFenReadSheBei(String bleStrName) {
        if (bleStrName.contains("KT8000")) {
            selectIndex = 1;
            bluetoothName = "卡尔KT8000读卡";
        } else if (bleStrName.contains("KT8003")) {
            selectIndex = 2;
            bluetoothName = "卡尔KT8003读卡";
        } else if (bleStrName.contains("SR")) {
            selectIndex = 3;
            bluetoothName = "森锐读卡";
        } else if (bleStrName.contains("HOD")) {
            selectIndex = 4;
            bluetoothName = "恒鸿达读卡";
        } else if (bleStrName.contains("DJLM")) {
            mHandler.sendEmptyMessage(0); // 取消搜索
            selectIndex = 5;
            bluetoothName = "店家联盟读卡";
        }
        return selectIndex;
    }

    // 初始化数据
    private void initData() {
        if (BluetoothManager.isBluetoothSupported()) {
            if (!BluetoothManager.isBluetoothEnabled()) {
                turnOnBluetooth();
            } else {
                startSeach();
            }
        }
    }

    private static final long SCAN_PERIOD = 8000;

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ba.stopLeScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);
            ba.startLeScan(mLeScanCallback);
        } else {
            pb_ble.setVisibility(View.GONE);
        }
    }

    /**
     * 搜索蓝牙(djlm)
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
                    Message message = new Message();
                    message.what = 2;
                    message.obj = device;
                    mHandler.sendMessage(message);
                }
            };

    /**
     * 终止写卡
     *
     * @param bleType
     */
    private void closeReadCard(int bleType) {
        Log.e("项目异常写卡", "------closeReadCard------" + bleType);
        switch (bleType) {
            case 1:
                if (kt8000Write != null) {
                    kt8000Write.closeClient();
                }
                break;
            case 2:
                if (kt8003Write != null) {
                    kt8003Write.stopConnect();
                }
                break;
            case 5:
                if (mDjlmWrite != null) {
                    mDjlmWrite.disConnect();
                }
                break;
        }
    }

    /**
     * 监听返回键和弹窗消失事件
     */
    public void stopRead() {
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                finish();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                closeReadCard(selectIndex);
                dialog.dismiss();
                return true;
            }
        });
    }

    private void dismissDialog() {
        Log.e("项目异常写卡", "------dismissDialog-----");
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    /**
     * 读取iccid失败之后关闭界面
     *
     * @param count
     * @param result
     */
    private void showMsg(int count, final String result) {
        Message msg = Message.obtain(); //从全局池中返回一个message实例，避免多次创建message（如new Message）
        msg.obj = result;

        // 显示Toast
        msg.what = 111; //标志消息的标志

        mHandler.sendMessage(msg);

    }

    //*******************************************************************************
    private BluetoothDevice remoteDevice;
    private ProgressBar pb_ble;
    private ArrayList<String> bleNameList = new ArrayList<>();
    private ArrayList<String> bleAddressList = new ArrayList<>();
    private BleAdapter bleAdapter;
    // 配对弹窗监听
    private ListView lv_ble;
    private LinearLayout ll_shebei;
    private String bleAddress;
    private String bleName;


    private MyUsualyDialog dialog;
    private BtReaderClient mClient;
    private BtReadClient mBtReadClient;
    private BluetoothAdapter ba;

    private String bluetoothName = "";
    private String bluetoothType = "";
    private int selectIndex = 0;

    public SYDBlueReaderHelper mIdUtil = null;
    public Busi_Idcard_device midHandler = null;
    private Kt8000Write kt8000Write;
    private Kt8003Write kt8003Write;
    private SenRuiWrite senRuiWrite;
    private HHDWrite mHHDWrite;
    private DjlmWrite mDjlmWrite;

    /**
     * 获取写卡参数
     * 利用library里面的PrefUtils去app里面保存数据,不然获取不到数据
     */
    private void getReadNum(int readType) {
        switch (readType) {
            case 1:
            case 2:
                krServerIp = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.KRFTserverIp, "115.28.2.173");
                krAccount = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.KRFTaccount, "admin");
                krPassword = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.KRFTpassword, "www.kaer.cn");
                krftPort = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.KRFTport, "7443");
                Log.e("项目异常connect", "------krServerIp------" + krServerIp);
                break;
            case 3:
                srSeverIp = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.SRserverIp, "id.esaleb.com");
                srAccount = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.SRaccount, "test01");
                srPwd = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.SRpassword, "12315aA..1");
                srPort = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.SRport, "6100");
                srKey = PrefReadCardTools.getString(WriteCardActivity.this, ConstantsValue.SRkey, "FE870B0163113409C134283661490AEF");
                Log.e("项目异常connect", "------srSeverIp------" + srSeverIp);
                break;
        }
    }


    /**
     * 搜索已配对蓝牙
     */
    private void SearchBts() {
        pb_ble.setVisibility(View.VISIBLE);
        Set<BluetoothDevice> pairedDevices = ba.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                strNam += device.getName();
                strPeiDuiNam += device.getName();
                String blueName = device.getName();
                String blueAddress = device.getAddress();

                // 检测配对设备,如果包含制定字符串就去连接读卡器
                bleNameList.add(blueName);
                bleAddressList.add(blueAddress);
                bleAdapter.notifyDataSetChanged();

                if (bleNameList.size() == pairedDevices.size()) {
                    // 附近蓝牙搜索
                    scanLeDevice(true);
                }
            }
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    pb_ble.setVisibility(View.GONE);
                    ba.stopLeScan(mLeScanCallback);
                    break;
                case 1:
                    String err = (String) msg.obj;
                    Log.e("读卡结果", "------err------" + err);
                    if (!TextUtils.isEmpty(err)) {
                        ToastUtils.showShortToast(WriteCardActivity.this, err);
                    }
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    finish();
                    break;
                case 2:
                    BluetoothDevice device = (BluetoothDevice) msg.obj;
                    pb_ble.setVisibility(View.VISIBLE);
                    Log.e("蓝牙异常", device.getName() + "搜索=====:" + device.getAddress());
                    mHandler.sendEmptyMessageDelayed(0, 6000);
                    String buleName = device.getName();
                    if (bleNameList != null) {
                        if (buleName != null && !TextUtils.isEmpty(buleName) && !"null".equals(buleName)) {
                            Log.e("蓝牙异常", "strNam=====:" + strNam);
                            if (!strNam.contains(buleName)) {
                                strNam += buleName; // 新增的继续拼接
                                // 如果蓝牙民称不包含就添加
                                Log.e("蓝牙异常", device.getName() + "=====添加=====:" + device.getAddress());
                                bleNameList.add(buleName);
                                bleAddressList.add(device.getAddress());
                                bleAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                    break;
                case 111:
                    final String msgResult1 = (String) msg.obj;
                    ToastUtils.showShortToast(WriteCardActivity.this, msgResult1);
                    finish();
                    break;
            }
        }
    };

}
